<template>
  <div class="register-container">
    <a-form
      :model="form"
      :rules="rules"
      layout="vertical"
      @finish="validateEmailCaptcha"
      class="password-form"
    >
      <a-form-item
        label="账号"
        name="username"
      >
        <a-input
          v-model:value="form.username"
          placeholder="请输入账号"
          size="large"
        >
          <template #prefix>
            <user-outlined />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
      >
        <a-input-password
          v-model:value="form.password"
          placeholder="8-20位字母、数字组合"
          size="large"
        >
          <template #prefix>
            <lock-outlined />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item
        label="邮箱"
        name="email"
      >
        <a-input
          v-model:value="form.email"
          placeholder="请输入邮箱"
          size="large"
        >
          <template #prefix>
            <mail-outlined />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item
        label="验证码"
        name="code"
      >
        <div style="display: flex; align-items: center">
          <a-input
            v-model:value="form.code"
            placeholder="请输入验证码"
            size="large"
            style="flex: 1; margin-right: 10px"
          >
            <template #prefix>
              <safety-certificate-outlined />
            </template>
          </a-input>

          <a-button
            type="primary"
            @click="handleSendCode"
            :loading="sendingCode"
            size="large"
            :disabled="isCountingDown"
            style="flex: 0 0 30%"
          >
            {{ isCountingDown ? `重新发送(${countdown}s)` : '发送验证码' }}
          </a-button>
        </div>
      </a-form-item>

      <a-form-item>
        <a-button
          type="primary"
          html-type="submit"
          :loading="isSubmitting"
          size="large"
          block
          :disabled="isSubmitting"
        >
          注册
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { PlatformRegisterReqVO } from '@/types/auth'
import { checkEmailCaptcha, sendEmailCaptcha } from '@/api/captcha'
import { message } from 'ant-design-vue'
import {
  LockOutlined,
  UserOutlined,
  MailOutlined,
  SafetyCertificateOutlined
} from '@ant-design/icons-vue'
import { registerUser } from '@/api/auth'

const router = useRouter()

const isSubmitting = ref(false)
const isCountingDown = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)

const form = reactive<PlatformRegisterReqVO>({
  username: '',
  password: '',
  email: '',
  code: '',
  uuid: ''
})

/**
 * 验证邮箱
 */
const validateEmail = async (_rule: any, value: string) => {
  if (!value) {
    return Promise.reject('请输入邮箱')
  }

  // 验证邮箱格式
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailReg.test(value)) {
    return Promise.reject('请输入有效的邮箱地址')
  }

  return Promise.resolve()
}

/**
 * 验证密码
 */
const validatePass = async (_rule: any, value: string) => {
  if (value === '') {
    return Promise.reject('请输入密码')
  }
  if (!/^(?=.*[a-zA-Z])(?=.*\d).{8,20}$/.test(value)) {
    return Promise.reject('8-20位字母和数字组合')
  }
  return Promise.resolve()
}

const rules = {
  username: [
    {
      required: true,
      message: '请输入账号',
      trigger: 'blur'
    }
  ],

  password: [
    {
      required: true,
      validator: validatePass,
      trigger: 'blur'
    }
  ],

  email: [
    {
      required: true,
      validator: validateEmail,
      trigger: 'blur'
    }
  ],

  code: [
    {
      required: true,
      message: '请输入验证码',
      trigger: 'blur'
    }
  ]
}

/**
 * 注册
 */
const handleRegister = async () => {
  if (!form.username || !form.password || !form.email || !form.code || !form.uuid) {
    message.error('请输入完整信息')
    isSubmitting.value = true
    return
  }

  try {
    await registerUser(form)
    message.success('注册成功，请登录')
    isSubmitting.value = false
    router.push('/')
  } catch (error) {
    form.uuid = ''
    form.code = ''
  } finally {
    isSubmitting.value = false
  }
}

/**
 * 校验验证码
 */
const validateEmailCaptcha = async () => {
  isSubmitting.value = true
  const res = await checkEmailCaptcha(form.email, form.code, form.uuid)
  if (!res) {
    form.uuid = ''
    isSubmitting.value = false
    message.error('验证码错误，请重新发送验证码进行校验')
    return
  }

  handleRegister()
}

/**
 * 开始倒计时
 */
const startCountdown = () => {
  isCountingDown.value = true
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      isCountingDown.value = false
      clearInterval(timer)
    }
  }, 1000)
}

/**
 * 发送验证码
 */
const handleSendCode = async () => {
  if (!form.email) {
    message.error('请输入完整邮箱地址')
    return
  }

  // 验证邮箱格式
  const emailReg = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailReg.test(form.email)) {
    message.error('请输入有效的邮箱地址')
    return
  }

  sendingCode.value = true
  const uuid = await sendEmailCaptcha(form.email)

  if (!uuid) {
    message.error('发送验证码失败，请重新发送校验')
    sendingCode.value = false
    return
  }

  form.uuid = uuid
  message.success('验证码已发送')
  startCountdown()
  sendingCode.value = false
}
</script>

<style scoped>
.register-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 40px 24px;
}

.captcha-form-item {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
</style>
